//
//  GasQrVC.m
//  NtoccDriverNew
//
//  Created by niyongsheng on 2022/10/18.
//  Copyright © 2022 GCY. All rights reserved.
//

#import "GasQrVC.h"
#import "GasMoneyVC.h"
#import "GasStationDriverManager.h"
#import "GasSpendListModel.h"
#import "GasConfirmVC.h"
#import "GasConfirmModel.h"
#import "FFPopup.h"
#import "GasConfirmAlertView.h"

@interface GasQrVC ()
@property (weak, nonatomic) IBOutlet UIImageView *qrIV;
@property (weak, nonatomic) IBOutlet UILabel *moneyL;

@property (strong, nonatomic) GasConfirmAlertView *confirmAlertV;
@property (strong, nonatomic) FFPopup *popup;

@property (assign, nonatomic) NSInteger secondCount;

@end

@implementation GasQrVC
// 循环定时器
static dispatch_source_t _timer;

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"加油二维码";
    
    _moneyL.text = [NSString stringWithFormat:@"可用余额 ( 元 )：%@元", [GSDDetailUserInfo.oilCard isNotBlank] ? GSDDetailUserInfo.oilCard : @"0.00"];
    if ([_qrUrl isNotBlank] && [_serialNo isNotBlank]) {
        [self.qrIV setImageWithURL:[NSURL URLWithString:_qrUrl] placeholder:[UIImage imageNamed:@"gas_qr_code_bg"]];
        [self startCycleTimer:_serialNo];
        
    } else {
        [self getQrData];
    }
}

- (void)getQrData {
    NSString *urlStr = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],GasStationDriverPaymentOilNew);
    NSDictionary *branch = [UserDefaultUtil valueForKey:Login_Branch];
    NSDictionary *params = @{
        @"oil": _money,
        @"driverCode": branch[@"code"],
        @"branchCode": branch[@"branchCode"],
    };
    @weakify(self)
    [HTTPManager postNetworkRequest:urlStr
                     withParameter:params
                            withVC:[UIViewController new]
                           netName:@"加油二维码"
                           success:^(id response, NSString *msg) {
        @strongify(self)
        [self.qrIV setImageWithURL:[NSURL URLWithString:response[@"filePath"]] placeholder:[UIImage imageNamed:@"gas_qr_code_bg"]];
        [self startCycleTimer:[response stringValueForKey:@"serialNo" default:@""]];
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)selectPayResult:(NSString *)orderCode {
    self.secondCount += 5;
    if (self.secondCount >= 60*5) {
        self.confirmAlertV.isSuccess = NO;
        self.confirmAlertV.msg = @"查询订单状态超时！";
        [self.popup showWithLayout:FFPopupLayoutMake(FFPopupHorizontalLayout_Center, FFPopupVerticalLayout_Center)];
    }
    
    NSString *urlStr = CJStringWithFormat(@"%@%@/%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], GasStationPayment,  orderCode);
    @weakify(self)
    [HTTPManager getNetworkRequest:urlStr
                     withParameter:nil
                            withVC:self
                           netName:@"查询付款结果"
                           success:^(id response, NSString *msg) {
        @strongify(self)
        GasConfirmModel *model = [GasConfirmModel mj_objectWithKeyValues:response];
        if (model.transactionStatus.integerValue == 1) { // 1支付中
            GasConfirmVC *vc = [GasConfirmVC new];
            vc.model = model;
            [self.navigationController pushViewController:vc animated:YES];
            
        } else if (model.transactionStatus.integerValue == 4) { // 4已取消
            self.confirmAlertV.isSuccess = NO;
            self.confirmAlertV.msg = @"订单已取消！";
            [self.popup showWithLayout:FFPopupLayoutMake(FFPopupHorizontalLayout_Center, FFPopupVerticalLayout_Center)];
        }
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)startCycleTimer:(NSString *)orderCode {
    NSTimeInterval second = 5;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 2 * NSEC_PER_SEC), second * NSEC_PER_SEC, 0);
    // 定时器触发事件
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self selectPayResult:orderCode];
        });
    });

    dispatch_resume(_timer);
}

- (void)dealloc {
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (FFPopup *)popup {
    if (!_popup) {
        _popup = [FFPopup popupWithContentView:self.confirmAlertV showType:FFPopupShowType_GrowIn dismissType:FFPopupDismissType_ShrinkOut maskType:FFPopupMaskType_Dimmed dismissOnBackgroundTouch:NO dismissOnContentTouch:NO];
    }
    return _popup;
}

- (GasConfirmAlertView *)confirmAlertV {
    if (!_confirmAlertV) {
        CGFloat width = 300.0*ScreenW/375.0;
        CGFloat height = 240.0*ScreenW/375.0;
        _confirmAlertV = [[GasConfirmAlertView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        @weakify(self)
        _confirmAlertV.block = ^(int index) {
            @strongify(self)
            [self.popup dismissAnimated:YES];
            [self.navigationController popToRootViewControllerAnimated:YES];
        };
    }
    return _confirmAlertV;
}

@end
